using System;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using ProgramLauncher.Models;

namespace ProgramLauncher.Utils
{
    public static class ConfigManager
    {
        private static readonly string CONFIG_FILE = Path.Combine(
            AppDomain.CurrentDomain.BaseDirectory, 
            "config.json"
        );
        private static readonly object ConfigLock = new object();
        private static readonly JsonSerializerSettings JsonSettings = new JsonSerializerSettings
        {
            Formatting = Formatting.Indented,
            NullValueHandling = NullValueHandling.Ignore
        };
        private const int MAX_BACKUPS = 5;  // 最大备份数量

        /// <summary>
        /// 读取配置文件
        /// </summary>
        public static AppConfig LoadConfig()
        {
            string configPath = CONFIG_FILE;
            
            try
            {
                if (!File.Exists(configPath))
                {
                    return new AppConfig();
                }

                string jsonContent = File.ReadAllText(configPath, Encoding.UTF8);
                var config = JsonConvert.DeserializeObject<AppConfig>(jsonContent, JsonSettings);
                return config ?? new AppConfig();
            }
            catch (Exception ex)
            {
                LogManager.LogError("加载配置文件失败", ex);
                
                // 尝试从最近的备份恢复
                for (int i = 1; i <= MAX_BACKUPS; i++)
                {
                    string backupPath = GetBackupPath(i);
                    if (File.Exists(backupPath))
                    {
                        try
                        {
                            string backupContent = File.ReadAllText(backupPath, Encoding.UTF8);
                            var config = JsonConvert.DeserializeObject<AppConfig>(backupContent, JsonSettings);
                            if (config != null)
                            {
                                LogManager.LogInfo($"已从备份文件 {i} 恢复配置");
                                return config;
                            }
                        }
                        catch
                        {
                            // 继续尝试下一个备份
                            continue;
                        }
                    }
                }

                // 如果所有备份都无法加载，返回新的配置
                return new AppConfig();
            }
        }

        /// <summary>
        /// 保存配置到文件
        /// </summary>
        public static void SaveConfig(AppConfig config)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            string configPath = CONFIG_FILE;
            string jsonContent = JsonConvert.SerializeObject(config, JsonSettings);

            try
            {
                // 如果配置文件存在，先创建备份
                if (File.Exists(configPath))
                {
                    // 移动现有的备份文件
                    for (int i = MAX_BACKUPS - 1; i > 0; i--)
                    {
                        string currentBackup = GetBackupPath(i);
                        string nextBackup = GetBackupPath(i + 1);

                        if (File.Exists(currentBackup))
                        {
                            if (File.Exists(nextBackup))
                            {
                                File.Delete(nextBackup);
                            }
                            File.Move(currentBackup, nextBackup);
                        }
                    }

                    // 将当前配置文件复制为第一个备份
                    File.Copy(configPath, GetBackupPath(1), true);
                }

                // 保存新的配置文件
                File.WriteAllText(configPath, jsonContent, Encoding.UTF8);
                LogManager.LogInfo("配置已保存");
            }
            catch (Exception ex)
            {
                LogManager.LogError("保存配置文件失败", ex);
                throw;
            }
        }

        /// <summary>
        /// 验证配置有效性
        /// </summary>
        private static bool ValidateConfig(AppConfig config)
        {
            if (config?.Buttons == null)
                return false;

            foreach (var button in config.Buttons)
            {
                if (string.IsNullOrWhiteSpace(button.Name) ||
                    string.IsNullOrWhiteSpace(button.ProgramPath))
                    return false;
            }

            return true;
        }

        /// <summary>
        /// 创建默认配置
        /// </summary>
        private static AppConfig CreateDefaultConfig()
        {
            return new AppConfig
            {
                Buttons = new System.Collections.Generic.List<ButtonConfig>
                {
                    new ButtonConfig
                    {
                        Name = "示例按钮",
                        ProgramPath = Path.Combine(Environment.SystemDirectory, "notepad.exe")
                    }
                }
            };
        }

        private static string GetBackupPath(int index)
        {
            string appPath = AppDomain.CurrentDomain.BaseDirectory;
            return Path.Combine(appPath, $"config.{index}.bak");
        }
    }
}